using UnityEngine;

namespace Math
{
    public static class Intersect
    {
        public static bool PointInPlane(Plane plane, Vector3 point)
        {
            return (plane.Dot(point)<0.0f)?false:true;
        }

        public static bool PointInFrustum(Plane[] planes, Vector3 point)
        {
            for (int i=0; i<6; ++i)
                if (planes[i].Dot(point)<0.0f) return false;
            return true;
        }

        public static bool SphereInPlane(Plane plane, Vector3 center, float radius)
        {
            return ((plane.Dot(center)+radius)<0.0f)?false:true;
        }

        public static bool SphereInFrustum(Plane[] planes, Vector3 center, float radius)
        {
            for (int i=0; i<6; ++i)
                if ((planes[i].Dot(center)+radius)<0.0f) return false;
            return true;
        }

        public static bool BoxInPlane(Plane plane, Vector3 min, Vector3 max)
        {
            int outside = 0;
            outside += (plane.Dot(min.x, min.y, min.z)<0.0f)?1:0;
            outside += (plane.Dot(max.x, min.y, min.z)<0.0f)?1:0;
            outside += (plane.Dot(min.x, max.y, min.z)<0.0f)?1:0;
            outside += (plane.Dot(max.x, max.y, min.z)<0.0f)?1:0;
            outside += (plane.Dot(min.x, min.y, max.z)<0.0f)?1:0;
            outside += (plane.Dot(max.x, min.y, max.z)<0.0f)?1:0;
            outside += (plane.Dot(min.x, max.y, max.z)<0.0f)?1:0;
            outside += (plane.Dot(max.x, max.y, max.z)<0.0f)?1:0;
            return (outside!=8);
        }

        public static bool BoxInFrustum(Plane[] planes, Vector3 min, Vector3 max)
        {
            for (int i=0; i<6; ++i)
            {
                int outside = 0;
                outside += (planes[i].Dot(min.x, min.y, min.z)<0.0f)?1:0;
                outside += (planes[i].Dot(max.x, min.y, min.z)<0.0f)?1:0;
                outside += (planes[i].Dot(min.x, max.y, min.z)<0.0f)?1:0;
                outside += (planes[i].Dot(max.x, max.y, min.z)<0.0f)?1:0;
                outside += (planes[i].Dot(min.x, min.y, max.z)<0.0f)?1:0;
                outside += (planes[i].Dot(max.x, min.y, max.z)<0.0f)?1:0;
                outside += (planes[i].Dot(min.x, max.y, max.z)<0.0f)?1:0;
                outside += (planes[i].Dot(max.x, max.y, max.z)<0.0f)?1:0;
                if (outside==8) return false;
            }
            return true;
        }
    }
}